package com.qf.exception;

import com.qf.dto.ApiResult;
import com.qf.enums.ApiEnum;
import com.qf.utils.R;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: chen
 * @Date: 2021/3/2 9:12 AM
 * @Version 1.0
 */
//需求：是来改造原本的异常情况下的返回
    //被ControllerAdvice修饰的类 可以重新返回结果
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    //注解是用来识别你要拦截的异常类
    @ExceptionHandler(value = ArithmeticException.class)
    public ApiResult arithmeticException(ArithmeticException e){
        //在控制台输出异常信息
        e.printStackTrace();
        return R.fail(e.getMessage());
    }


    @ExceptionHandler(value = TooManyResultsException.class)
    public ApiResult tooManyResultsException(TooManyResultsException e){
        //在控制台输出异常信息
        e.printStackTrace();
        return R.fail(ApiEnum.SELECT_TOO_MANY);
    }


    //处理数组脚标越界异常/空指针异常
    @ExceptionHandler(value = IndexOutOfBoundsException.class)
    public ApiResult indexOutOfBoundsException(IndexOutOfBoundsException e){
        //在控制台输出异常信息
        e.printStackTrace();
        return R.fail(e.getMessage());
    }
    @ExceptionHandler(value = NullPointerException.class)
    public ApiResult nullPointerException(NullPointerException e){
        //在控制台输出异常信息
        e.printStackTrace();
        return R.fail(e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public ApiResult exception(Exception e){
        //在控制台输出异常信息
        e.printStackTrace();
        if(e instanceof TooManyResultsException ){
            return R.fail(ApiEnum.SELECT_TOO_MANY);
        }
        if(e instanceof MyBatisSystemException){
            return R.fail(e .getMessage());
        }
        return R.fail(e.getMessage());
    }

    @ExceptionHandler(value = GlobalException.class)
    public ApiResult globalException(GlobalException e){
        e.printStackTrace();
        return R.fail(e.getApiEnum());
    }





}
